package org.example.Interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.Util.JWTUtil;
import org.example.Util.UserUtil;
import org.example.core.Dto.common.Result;
import org.example.core.Dto.common.ResultCode;
import org.example.core.pojo.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class UserLoadInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        log.info("获取的token：{}", token);
        boolean authed = false;
        try {
            if (StrUtil.isNotBlank(token)) {
                if (JWTUtil.VerifyJwt(token)) { //校验token
                    User user = JWTUtil.getUser(token);
                    UserUtil.setUser(user);
                    authed = true;
                }
            }
            if (!authed) {
                writeErrMsg(response);
                return false;
            }
        } catch (Exception e) {
            writeErrMsg(response);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.rmUser();
    }

    public static void writeErrMsg(HttpServletResponse response) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        try (PrintWriter writer = response.getWriter()) {
            String jsonResponse = JSONUtil.toJsonStr(Result.failed(ResultCode.ACCESS_UNAUTHORIZED));
            writer.print(jsonResponse);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}